package de.mhu.mandalaui.attributes;

import java.io.PrintWriter;

import de.mhu.mandalaui.Window;
import de.mhu.mandalaui.bind.DataRow;
import de.mhu.mandalaui.bind.Element;
import de.mhus.lib.lang.Raw;

public class Attribute extends Element {

	@Override
	public void renderBindCall(PrintWriter out) {
		renderAttributeName(out);
	}

	public void renderAttributeName(PrintWriter out) {
		Window window = getWindow();
		if (window != null) {
			out.print(window.getId());
			out.print(".");
		}
		out.print(getId());
	}
	
	@Override
	public void renderFunctionImplementation(PrintWriter out) {
		out.print("ko.observable()");
	}

	public void renderSet(PrintWriter out, Object value) {
		
		if (value == null) {
			renderAttributeName(out);
			out.println("(undefined);");
			return;
		}
		
		if (value instanceof Number) {
			renderAttributeName(out);
			out.print("(");
			out.print((Number)value);
			out.println(");");
			return;
		}
		
		if (value instanceof String) {
			renderAttributeName(out);
			out.print("('");
			out.print(encode(value.toString()));
			out.println("');");
			return;
		}

		if (value instanceof Raw ) {
			renderAttributeName(out);
			out.print("(");
			out.print(value.toString());
			out.println(");");
			return;
		}
		
		if (value instanceof DataRow) {
			renderAttributeName(out);
			out.print("(");
			out.print( ((DataRow)value).toJSONString() );
			out.println(");");
			return;
		}

		if (value instanceof Element ) {
			renderAttributeName(out);
			out.print("(");
			((Element)value).renderGet(out);
			out.println(");");
			return;
		}
		
		renderAttributeName(out);
		out.print("('");
		out.print(encode(value.toString()));
		out.println("');");

	}

	private String encode(String in) {
		if (in == null) return "";
		if (in.indexOf('\\') >= 0) in = in.replaceAll("\\\\", "\\\\\\\\'");
		if (in.indexOf('\'') >= 0) in = in.replaceAll("'", "\\\\'");
		return in;
	}

	@Override
	public void renderGet(PrintWriter out) {
		renderAttributeName(out);
		out.print("()");
	}
	
	
}
